import {
  x as C,
  r as ae,
  i as u,
  o as i,
  a as z,
  m as e,
  l,
  k as y,
  F as J,
  j as X,
  b as f,
  t as V,
  e as s,
  u as j,
  O as K,
  P as R,
  Q as ee,
  B as g,
} from "./index-abba05ce.js";

const Ye = { class: "admin-lists" },
  Ze = { class: "border-none mt-2" },
  Je = { class: "d-flex flex-wrap items-center" },
  Xe = { class: "filters" },
  Ke = { class: "border-none mt-3" },
  Qe = { class: "d-flex justify-content-end mt-4" };

// 格式化时间戳
const formatTimestamp = (value) => {
  if (!value) return "-";
  const timestamp = String(value).length === 10 ? Number(value) * 1e3 : Number(value);
  if (!timestamp || Number.isNaN(timestamp)) return "-";
  const date = new Date(timestamp);
  if (Number.isNaN(date.getTime())) return "-";
  const pad = (num) => `${num}`.padStart(2, "0");
  return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
};

const et = {
  __name: "index",
  setup() {
    // 筛选条件 - 根据spj_authentication表结构
    const filters = ae({ id: "", name: "", user_id: "", cate_id: "", status: "", describe: "" });
    // 表格数据 - 初始化为空数组，避免undefined
    const tableData = C([]);
    // 加载状态
    const loading = C(!1);
    // 分页信息 - 确保所有属性都有默认值
    const pagination = ae({ page: 1, pageSize: 20, total: 0 });
    
    // 添加一个安全的数据获取方法，确保返回的始终是有效的数组
    const getSafeArray = (data) => {
        if (!data) return [];
        if (Array.isArray(data)) return data;
        return [];
    };

    const buildParams = () => {
      const params = {
        page: pagination.page,
        page_size: pagination.pageSize,
      };
      if (filters.id) params.id = filters.id;
      if (filters.name) params.name = filters.name;
      if (filters.user_id) params.user_name = filters.user_id; // 修改为用户名称模糊搜索
      if (filters.cate_id) params.category_name = filters.cate_id; // 修改为领域名称模糊搜索
      if (filters.status !== "") params.status = filters.status;
      if (filters.describe) params.describe = filters.describe;
      return params;
    };

    const fetchList = async () => {
      tableData.value = []; // 每次调用前先清空并设置为有效数组
      loading.value = !0;
      try {
        // 确保buildParams返回有效对象
        const params = typeof buildParams === 'function' ? buildParams() : {};
        // 确保K.authentication和list方法存在
        if (!K || !K.authentication || typeof K.authentication.list !== 'function') {
            console.error("Authentication API not available");
            R.msgError("API服务不可用");
            return;
        }
        const res = await K.authentication.list(params);
        // 严格检查响应结构
        if (!res || typeof res !== 'object') {
            console.error("Invalid response structure");
            R.msgError("获取列表失败：响应格式错误");
            return;
        }
        if (res.error) {
            R.msgError(res.msg || "获取列表失败");
            return;
        }
        const data = res.data || {};
        // 使用安全的方法确保rawData始终是有效的数组
        const rawData = getSafeArray(data.data);
        // 确保map处理每个项目时不会出错，过滤掉无效数据
        tableData.value = rawData
            .filter(item => item && typeof item === 'object') // 只处理有效的对象
            .map(item => {
                // 处理information_json字段，支持JSON对象、字符串格式的JSON
                let information = [];
                try {
                    if (Array.isArray(item.information_json)) {
                        // 已经是数组
                        information = item.information_json;
                    } else if (typeof item.information_json === 'string') {
                        // 尝试解析字符串格式的JSON
                        const parsed = JSON.parse(item.information_json);
                        if (Array.isArray(parsed)) {
                            information = parsed;
                        }
                    }
                    // 确保最终是数组
                    if (!Array.isArray(information)) {
                        information = [];
                    }
                } catch (error) {
                    console.error("Error parsing information_json:", error, "item.information_json:", item.information_json);
                    information = [];
                }
                return {
                    id: item.id || '',
                    name: item.name || '',
                    user_id: item.user_id || '',
                    cate_id: item.cate_id || '',
                    status: item.status || 0,
                    describe: item.describe || '',
                    information: information,
                    create_time: item.create_time || '',
                    update_time: item.update_time || '',
                    user: item.user || {},
                    category: item.category || {}
                };
            });
        // 安全更新分页信息
        pagination.total = typeof data.total === 'number' ? data.total : 0;
        pagination.page = typeof data.page === 'number' ? data.page : pagination.page;
        pagination.pageSize = typeof data.pageSize === 'number' ? data.pageSize : pagination.pageSize;
      } catch (err) {
        console.error("fetch list error:", err);
        R.msgError("获取列表失败");
        tableData.value = []; // 确保总是设置为空数组
      } finally {
        loading.value = !1;
        
        // 执行最终数据验证
        try {
            // 再次确保tableData是有效的数组
            if (!Array.isArray(tableData.value)) {
                console.warn('数据验证失败: tableData不是数组');
                tableData.value = [];
                return;
            }
            
            // 验证并修复每一条记录
            tableData.value = tableData.value.map((item, index) => {
                // 确保每一项都是有效对象
                if (!item || typeof item !== 'object') {
                    console.warn(`第${index}条数据不是有效对象，已忽略`);
                    return null;
                }
                
                // 确保information字段始终是有效的数组
                if (item.information === undefined || item.information === null || !Array.isArray(item.information)) {
                    item.information = [];
                }
                
                return item;
            }).filter(Boolean); // 过滤掉null项
            
            console.log(`数据验证完成: 共有${tableData.value.length}条有效记录`);
        } catch (error) {
            console.error('数据验证过程发生错误:', error);
            tableData.value = []; // 出错时确保tableData为空数组
        }
      }
    };

    // 编辑认证
    const handleEdit = (row) => {
        try {
            if (!row || typeof row !== 'object' || !row.id) {
                console.error('无效的认证数据:', row);
                if (window.R && typeof window.R.msgError === 'function') {
                    window.R.msgError('数据异常，无法编辑');
                } else {
                    alert('数据异常，无法编辑');
                }
                return;
            }
            window.location.href = new URL(`/science/authentication/create?id=${row.id}`, window.location.origin).href;
        } catch (error) {
            console.error('处理编辑失败:', error);
            if (window.R && typeof window.R.msgError === 'function') {
                window.R.msgError('操作失败');
            }
        }
    };

    // 查看认证资料详情
    const handleViewInfo = (row) => {
      try {
        if (!row || typeof row !== 'object' || !row.information) {
          R.msgError('认证资料不存在');
          return;
        }
          console.log('row',infoContent);
        // 创建一个临时的弹窗来显示认证资料
        const infoContent = row.information
          .filter(item => item && typeof item === 'object')
          .map((item, index) => `
            <div class="info-item">
              <h4>${item.name || `资料 ${index + 1}`}</h4>
              ${item.file ? `<img src="${item.file.trim()}" style="max-width: 100%; max-height: 300px;" />` : '无文件'}
            </div>
          `)
          .join('');
          console.log('infoContent',infoContent);
        // 使用原生 alert 显示简化信息
        if (infoContent) {
          alert(`认证资料详情:\n${row.information.map(item => `${item.name || '资料'}: ${item.file || '无文件'}`).join('\n')}`);
        } else {
          R.msgInfo('认证资料为空');
        }
      } catch (error) {
        console.error('查看认证资料失败:', error);
        R.msgError('操作失败');
      }
    };

    const handleSearch = () => {
      pagination.page = 1;
      fetchList();
    };

    const resetFilters = () => {
      filters.id = "";
      filters.name = "";
      filters.user_id = "";
      filters.cate_id = "";
      filters.status = "";
      filters.describe = "";
      pagination.page = 1;
      fetchList();
    };

    const handlePageChange = (page) => {
      pagination.page = page;
      fetchList();
    };

    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      pagination.page = 1;
      fetchList();
    };

    // 初始加载数据
    fetchList();

    // 删除功能
    const handleDelete = async (row) => {
      try {
        // 使用 window.confirm 替代 Vue 的 $confirm
        const confirmResult = window.confirm('确定要删除这条认证记录吗？删除后将无法恢复！');
        if (confirmResult) {
            // 调用删除API
            const res = await K.authentication.delete({id: row.id});
            if (res.error) {
                R.msgError(res.msg || '删除失败');
                return;
            }

            R.msgSuccess('删除成功');
            fetchList(); // 重新获取列表数据
        }
      } catch (err) {
        console.error('delete error', err);
        R.msgError('删除失败');
      }
    };

    return {
      filters,
      tableData,
      loading,
      pagination,
      handleSearch,
      resetFilters,
      handlePageChange,
      handleSizeChange,
      handleEdit,
      handleDelete,
      handleViewInfo,
      formatTimestamp
    };
  },
  render() {
    const d = this,
      a = u("el-card"),
      w = u("el-form"),
      p = u("el-form-item"),
      k = u("el-input"),
      b = u("el-select"),
      h = u("el-option"),
      q = u("el-button"),
      N = u("el-table"),
      m = u("el-table-column"),
      $ = u("el-tag"),
      P = u("el-image"),
      L = u("el-pagination"),
      T = ee("loading");
    return (
      i(),
      z("div", Ye, [
        e(
          a,
          { class: "border-none mt-2", shadow: "never" },
          {
            default: l(() => [
              f("div", Je, [
                f("div", { class: "filters d-flex align-items-center" }),
                e(
                  w,
                  { 
                    model: d.filters,
                    inline: "",
                    class: "d-inline-flex flex-wrap"
                  },
                  {
                    default: l(() => [
                      e(
                        p,
                        { label: "ID", prop: "id", class: "mr-3" },
                        {
                          default: l(() => [
                            e(
                              k,
                              { 
                                modelValue: d.filters.id,
                                "onUpdate:modelValue":
                                  d.$_id || (d.$_id = (t) => (d.filters.id = t)),
                                clearable: "",
                                placeholder: "请输入ID",
                                style: { width: '150px' },
                                onKeyup:
                                  d.$_enterId ||
                                  (d.$_enterId = (t) =>
                                    t.key === "Enter" && d.handleSearch()),
                              },
                              null,
                              8,
                              ["modelValue", "onKeyup"],
                            ),
                          ]),
                          _: 1,
                        },
                      ),
                      // 添加名称搜索框
                      e(
                        p,
                        { label: "名称", prop: "name", class: "mr-3" },
                        {
                          default: l(() => [
                            e(
                              k,
                              { 
                                modelValue: d.filters.name,
                                "onUpdate:modelValue":
                                  d.$_name || (d.$_name = (t) => (d.filters.name = t)),
                                clearable: "",
                                placeholder: "请输入名称",
                                style: { width: '150px' },
                                onKeyup:
                                  d.$_enterName ||
                                  (d.$_enterName = (t) =>
                                    t.key === "Enter" && d.handleSearch()),
                              },
                              null,
                              8,
                              ["modelValue", "onKeyup"],
                            ),
                          ]),
                          _: 1,
                        },
                      ),
                      e(
                        p,
                        { label: "用户名称", prop: "user_id", class: "mr-3" },
                        {
                          default: l(() => [
                            e(
                              k,
                              { 
                                modelValue: d.filters.user_id,
                                "onUpdate:modelValue":
                                  d.$_user_id || (d.$_user_id = (t) => (d.filters.user_id = t)),
                                clearable: "",
                                placeholder: "请输入用户名称",
                                style: { width: '150px' },
                                onKeyup:
                                       d.$_enterUserId ||
                                       (d.$_enterUserId = (t) =>
                                         t.key === "Enter" && d.handleSearch()),
                              },
                              null,
                              8,
                              ["modelValue", "onKeyup"],
                            ),
                          ]),
                          _: 1,
                        },
                      ),
                      e(
                        p,
                        { label: "领域名称", prop: "cate_id", class: "mr-3" },
                        {
                          default: l(() => [
                            e(
                              k,
                              { 
                                modelValue: d.filters.cate_id,
                                "onUpdate:modelValue":
                                  d.$_cate_id || (d.$_cate_id = (t) => (d.filters.cate_id = t)),
                                clearable: "",
                                placeholder: "请输入领域名称",
                                style: { width: '150px' },
                                onKeyup:
                                       d.$_enterCateId ||
                                       (d.$_enterCateId = (t) =>
                                         t.key === "Enter" && d.handleSearch()),
                              },
                              null,
                              8,
                              ["modelValue", "onKeyup"],
                            ),
                          ]),
                          _: 1,
                        },
                      ),
                      e(
                        p,
                        { label: "状态", prop: "status", class: "mr-3" },
                        {
                          default: l(() => [
                            e(
                              b,
                              { 
                                modelValue: d.filters.status,
                                "onUpdate:modelValue":
                                  d.$_status || (d.$_status = (t) => (d.filters.status = t)),
                                clearable: "",
                                placeholder: "请选择状态",
                                style: { width: '150px' },
                              },
                              {
                                default: l(() => [
                                  e(h, { label: "未审核", value: 0 }),
                                  e(h, { label: "通过", value: 1 }),
                                  e(h, { label: "拒绝", value: 2 }),
                                ]),
                                _: 1,
                              },
                              8,
                              ["modelValue"],
                            ),
                          ]),
                          _: 1,
                        },
                      ),
                      e(
                        p,
                        { label: "描述", prop: "describe", class: "mr-3" },
                        {
                          default: l(() => [
                            e(
                              k,
                              { 
                                modelValue: d.filters.describe,
                                "onUpdate:modelValue":
                                  d.$_describe || (d.$_describe = (t) => (d.filters.describe = t)),
                                clearable: "",
                                placeholder: "请输入描述",
                                style: { width: '150px' },
                                onKeyup:
                                       d.$_enterDescribe ||
                                       (d.$_enterDescribe = (t) =>
                                         t.key === "Enter" && d.handleSearch()),
                              },
                              null,
                              8,
                              ["modelValue", "onKeyup"],
                            ),
                          ]),
                          _: 1,
                        },
                      ),
                      e(
                        p,
                        { class: "mr-3", style: { "margin-right": "8px" } },
                        {
                          default: l(() => [
                            e(
                              q,
                              {
                                type: "primary",
                                icon: "Search",
                                onClick: d.handleSearch,
                                size: "small",
                              },
                              {
                                default: l(() => [s("查询")]),
                                _: 1,
                              },
                              8,
                              ["onClick"],
                            ),
                            e(
                        q,
                        { icon: "Refresh", onClick: d.resetFilters, size: "small" },
                        {
                          default: l(() => [s("重置")]),
                          _: 1,
                        },
                        8,
                        ["onClick"],
                      ),
                          ]),
                          _: 1,
                        },
                      ),
                    ]),
                    _: 1,
                  },
                  8,
                  ["model"],
                ),
              ]),
            ]),
            _: 1,
          },
        ),
        e(
          a,
          { class: "border-none mt-3", shadow: "never" },
          {
            default: l(() => [
              g(
                e(
                  N,
                  {
                    data: (function() {
                      try {
                        // 确保d存在且是对象
                        if (!d || typeof d !== 'object') {
                          console.warn('表格配置对象不存在或无效');
                          return [];
                        }
                        // 确保tableData存在且是数组
                        const tableData = d.tableData;
                        if (!tableData || !Array.isArray(tableData)) {
                          console.warn('表格数据不存在或不是数组');
                          return [];
                        }
                        // 过滤并验证每一行数据
                        return tableData.filter(row => {
                          if (!row || typeof row !== 'object') {
                            return false;
                          }
                          // 确保information属性是有效数组
                          if (row.information !== undefined && !Array.isArray(row.information)) {
                            row.information = [];
                          }
                          return true;
                        });
                      } catch (error) {
                        console.error('处理表格数据时发生错误:', error);
                        return [];
                      }
                    })(),
                    size: "large",
                    stripe: "",
                    "row-key": "id",
                    "header-cell-style": {
                      background: "var(--el-bg-color-page)",
                    },
                  },
                  {
                    default: l(() => [
                      e(m, { prop: "id", label: "ID", width: "80" }),
                      e(m, { prop: "name", label: "姓名", width: "120" }),
                      // e(m, { prop: "user_id", label: "用户ID", width: "100" }, null, 8, []),
                        e(
                        m,
                        { label: "用户", width: "180" },
                        {
                          // 尝试使用原始结构，但增加错误处理
                          default: l(({ row }) => {
                            // 先确保row对象可用
                            if (!row) return [s(V('无数据'), 1)];
                            
                            // 尝试访问user对象的不同方式
                            let userName = '用户ID ' + (row.user_id || '未知');
                        
                            try {
                              // 最基本的访问方式
                              if (row.user && row.user.name) {
                                userName = row.user.name;
                                userName = userName + ('（ID:' + row.user_id + '）');
                              }
                            } catch (e) {
                              // 忽略错误，使用默认值
                            }
                            
                            return [s(V(userName), 1)];
                          }),
                          _: 1,
                        },
                      ),
                        e(
                        m,
                        { label: "领域", width: "180" },
                        {
                          // 尝试使用原始结构，但增加错误处理
                          default: l(({ row }) => {
                            // 先确保row对象可用
                            if (!row) return [s(V('无数据'), 1)];
                            
                            // 尝试访问category对象的不同方式
                            let categoryName = '领域ID ' + (row.cate_id || '未知');
                        
                            try {
                              // 最基本的访问方式
                              if (row.category && row.category.name) {
                                categoryName = row.category.name;
                                categoryName = categoryName + ('（ID:' + row.cate_id + '）');
                              }
                            } catch (e) {
                              // 忽略错误，使用默认值
                            }
                            
                            return [s(V(categoryName), 1)];
                          }),
                          _: 1,
                        },
                      ),
                      e(m, { prop: "cate_id", label: "领域ID", width: "100" }, null, 8, []),
                      e(m, { prop: "status", label: "状态", width: "100" }, {
                        default: l(({ row }) => {
                          const statusMap = {
                            0: '未审核',
                            1: '通过',
                            2: '拒绝'
                          };
                          return [s(statusMap[row.status] || '未知')];
                        }),
                        _: 1
                      }, null, 8, []),
                      e(m, { prop: "describe", label: "描述", width: "200", "show-overflow-tooltip": "" }, null, 8, []),
                      e(m, { label: "认证资料", width: "200" }, {
                        default: l(({ row }) => {
                          // 安全检查row对象
                          if (!row || typeof row !== 'object') {
                            return [s("数据无效")];
                          }
                          
                          // 尝试解析数据，先尝试information_json
                          let dataSource = [];
                          if (row.information_json) {
                            try {
                              // 检查是否为JSON字符串，如果是则解析
                              if (typeof row.information_json === 'string') {
                                dataSource = JSON.parse(row.information_json);
                              } else {
                                dataSource = row.information_json;
                              }
                            } catch (e) {
                              dataSource = [];
                            }
                          } else if (row.information) {
                            dataSource = row.information;
                          }
                          
                          // 确保是数组
                          if (!Array.isArray(dataSource)) {
                            dataSource = [];
                          }
                          
                          // 准备资料项数组
                          const infoItems = dataSource.filter(item => item && typeof item === 'object');
                          
                          if (infoItems.length > 0) {
                            // 创建资料项元素数组
                            const children = [];
                            
                            // 添加文本信息
                            children.push(s(`共${infoItems.length}项`));
                            
                            // 为每个有图片的资料项添加图片显示
                            infoItems.forEach((item, index) => {
                              if (item.file && typeof item.file === 'string') {
                                // 添加名称
                                if (item.name) {
                                  children.push(s(item.name || `资料 ${index + 1}`));
                                }
                                // 添加图片元素
                                children.push(z("div", {
                                  style: {
                                    marginBottom: '5px'
                                  }
                                }, [
                                  z("img", {
                                    src: item.file,
                                    style: {
                                      maxWidth: '100px',
                                      maxHeight: '100px',
                                      border: '1px solid #eee'
                                    }
                                  })
                                ]));
                              }
                            });
                            
                            // 如果没有图片，仍然显示名称列表
                            if (children.length === 1) { // 只有"共X项"文本
                              const names = infoItems.map((item, index) => 
                                item.name || `资料 ${index + 1}`
                              ).join(', ');
                              return [s(`共${infoItems.length}项: ${names}`)];
                            }
                            
                            // 返回包含图片的结果
                            return children;
                          } else {
                            return [s("暂无资料")];
                          }
                        }),
                        _: 1
                      }),

                      e(
                        m,
                        { label: "提交时间", width: "180" },
                        {
                          default: l(({ row: t }) => [
                            s(V(d.formatTimestamp ? d.formatTimestamp(t.create_time) : (t.create_time || "-"))),
                          ]),
                          _: 1,
                        },
                      ),
                      e(
                        m,
                        { label: "更新时间", width: "180" },
                        {
                          default: l(({ row: t }) => [
                            s(V(d.formatTimestamp ? d.formatTimestamp(t.update_time) : (t.update_time || "-"))),
                          ]),
                          _: 1,
                        },
                      ),

                      e(
                        m,
                        { label: "操作", width: "240", fixed: "right" },
                        {
                          default: l(({ row: t }) => [
                         
                            e(
                              q,
                              {
                                type: "primary",
                                size: "small",
                                style: { marginLeft: "10px" },
                                onClick: () => d.handleEdit(t)
                              },
                              {
                                default: l(() => [s("编辑")]),
                                _: 1,
                              },
                              8,
                              ["onClick"],
                            ),
                            e(
                              q,
                              {
                                type: "danger",
                                size: "small",
                                style: { marginLeft: "10px" },
                                onClick: () => d.handleDelete(t)
                              },
                              {
                                default: l(() => [s("删除")]),
                                _: 1,
                              },
                              8,
                              ["onClick"],
                            )
                          ]),
                          _: 1,
                        },
                      )
                      

                    ]),
                    _: 1,
                  },
                  8,
                  ["data", "header-cell-style"],
                ),
                [[T, d.loading]],
              ),
              f("div", Qe, [
                e(
                  L,
                  {
                    background: "",
                    layout: "total, sizes, prev, pager, next, jumper",
                    total: d.pagination.total,
                    "page-sizes": [10, 20, 50, 100],
                    "current-page": d.pagination.page,
                    "page-size": d.pagination.pageSize,
                    onCurrentChange: d.handlePageChange,
                    onSizeChange: d.handleSizeChange,
                    "hide-on-single-page": false,
                  },
                  null,
                  8,
                  [
                    "total",
                    "current-page",
                    "page-size",
                    "onCurrentChange",
                    "onSizeChange",
                    "hide-on-single-page",
                  ],
                ),
              ]),
            ]),
            _: 1,
          },
        ),
      ])
    );
  },
};

export { et as default };
